package org.xaviera.dict;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.xaviera.Document;
import org.xaviera.Field;

public class FileSystemDocumentDictionary implements Dictionary<Document> {

	private Map<Long, Field> fields;
	
	private Set<File> files;
	
	private Iterator<File> iterator;
	
	private DataInputStream input;
	
	public FileSystemDocumentDictionary(Dictionary<Field> dictionary, File file) {
		files = new HashSet<File>();
		files.add(file);
		init(dictionary);
	}
	
	public FileSystemDocumentDictionary(Dictionary<Field> dictionary, Collection<File> files) {
		this.files = new HashSet<File>(files);
		init(dictionary);
	}
	
	
	private void init(Dictionary<Field> dictionary) {
		fields = new HashMap<Long, Field>();
		while (dictionary.hasNext()) {
			Dictionary.Entry<Field> entry = dictionary.next();
			fields.put(entry.getId(), entry.getValue());
		}
		iterator = files.iterator();
	}
	
	
	@Override
	public boolean hasNext() {
		try {
			while (input == null || input.available() == 0) {
				// close previous input
				if (input != null) {
					input.close();
				}
				// has more files?
				if (iterator.hasNext()) {
					input = 
						new DataInputStream(
							new FileInputStream(iterator.next())
						);
				}
				// no more files to read
				else {
					return false;
				}
			}
			// data available!
			return true;
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	
	@Override
	public Dictionary.Entry<Document> next() {
//		long id = input.readLong();
//		int count = input.readInt();
//		for (int index=0; index<count; index++) {
//			Field field = fields.get(input.readLong());
//		}
		return null; //new InnerEntry(input.readLong(), value);
	}

	
	@Override
	public void close() {
		if (input != null) {
			try {
				input.close();
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
	private class InnerEntry implements Dictionary.Entry<Document> {

		private long id;
		
		private Document value;
		
		
		private InnerEntry(long id, Document value) {
			this.id = id;
			this.value = value;
		}
		
		@Override
		public long getId() {
			return id;
		}

		@Override
		public Document getValue() {
			return value;
		}
		
	}
	
	
}
